
package com.hlkj.pay.app.merchant.ext.impl.fuyou.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.hlkj.pay.app.merchant.ext.impl.fuyou.constant.FuYouConstant;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by Ricky on 2016/11/20.
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, Map<String, String> map) {
        StringBuffer result = new StringBuffer("");
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<>();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key;
            String value;
            key = it.next().toString();
            value = map.get(key);
            formparams.add(new BasicNameValuePair(key, value));
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, FuYouConstant.charset);
            httppost.setEntity(uefEntity);
            log.info("富友请求参数 url:{},params:{}", httppost.getURI(), uefEntity.toString());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null && result != null) {
                    result.append(EntityUtils.toString(entity, FuYouConstant.charset));
                }
            }
            finally {
                response.close();
            }
            String responseData = result.toString();
            log.info("富友返回参数 url:{},params:{}", httppost.getURI(), responseData);
            try {
                return URLDecoder.decode(responseData, FuYouConstant.charset);
            }
            catch (Exception e) {
                // 部分中文字符转换
                log.info("富友返回参数解析报错 特殊中文字符转换 url:{},params:{}", httppost.getURI(), responseData);
                try {
                    responseData = responseData.replace("，", ",");
                    return URLDecoder.decode(responseData, FuYouConstant.charset);
                }
                catch (Exception e1) {
                    log.info("富友返回参数解析报错 直接返回 特殊中文字符转换 url:{},params:{}", httppost.getURI(), responseData);
                    return responseData;
                }
            }
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String response = "%3C%3Fxml+version%3D%221.0%22+encoding%3D%22GBK%22%3F%3E%0A%0A%3Cxml%3E%0A++%3Ctrace_no%3E%3C%2Ftrace_no%3E%0A++%3Cmchnt_name%3E%3C%2Fmchnt_name%3E%0A++%3Cfy_mchnt_cd%3E%3C%2Ffy_mchnt_cd%3E%0A++%3Cret_msg%3E%B2%CE%CA%FD%B8%F1%CA%BD%B4%ED%CE%F3%3Acertif_id%B3%A4%B6%C8%CC%AB%B6%CC%3C%2Fret_msg%3E%0A++%3Cwxapp_mchnt_cd%3E%3C%2Fwxapp_mchnt_cd%3E%0A++%3Cis_effective_acnt%3E%3C%2Fis_effective_acnt%3E%0A++%3Cacnt_upd_no%3E%3C%2Facnt_upd_no%3E%0A++%3Cret_code%3E2001%3C%2Fret_code%3E%0A++%3Cwx_mchnt_cd%3E%3C%2Fwx_mchnt_cd%3E%0A++%3Cauto_buy_cd%3E%3C%2Fauto_buy_cd%3E%0A++%3Cauto_buy_msg%3E%3C%2Fauto_buy_msg%3E%0A++%3Cwechat_mchnt_cd%3E%3C%2Fwechat_mchnt_cd%3E%0A++%3Cacnt_upd_st%3E%3C%2Facnt_upd_st%3E%0A++%3Cacnt_upd_msg%3E%3C%2Facnt_upd_msg%3E%0A++%3Cacnt_upd_ts%3E%3C%2Facnt_upd_ts%3E%0A%3C%2Fxml%3E%0A";
        System.out.println(URLDecoder.decode(response, FuYouConstant.charset));
    }

}
